package org.whereiswally.net.url;

import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.io.StringWriter;
import java.net.URL;

import org.apache.commons.io.IOUtils;
import org.whereiswally.net.url.imp.PicasaURLDao;

public abstract class URLManager implements Serializable {

    private static URLManager instance = new PicasaURLDao();

    public static URLManager getInstance() {
	return instance;
    }

    /**
     * TODO: Mejorar para que me retorne la cantidad de albunes publicos
     */

    public boolean checkURL(String urlS) {
	InputStream is = null;
	URL url = null;
	StringWriter writer = null;
	try {
	    url = new URL(makeURL(urlS));
	    is = ((InputStream) url.getContent());
	    writer = new StringWriter();
	    IOUtils.copy(is, writer);
	    return checkURLSource(writer.toString());
	} catch (Exception e) {
	    // e.printStackTrace();
	} finally {
	    if (is != null) {
		try {
		    is.close();
		} catch (IOException e) {
		    e.printStackTrace();
		}
	    }
	    url = null;
	    if (writer != null) {
		try {
		    writer.close();
		} catch (IOException e) {
		    // TODO Auto-generated catch block
		    e.printStackTrace();
		}
	    }
	}

	return false;
    }

    protected abstract boolean checkURLSource(String source);

    protected abstract String makeURL(String source);

}
